<template>
  <a-drawer v-model:visible="visible" :title="model.id ? '访客管理详情' : '访客管理新增'" placement="right" :width="450">
    <a-form ref="formRef" :model="model" :rules="rules" :label-col="{ span: 7 }" @finish="onFinish">
      <a-form-item label="到访者" name="visitor">
        <a-input v-model:value="model.visitor" allowClear placeholder="到访者" :disabled="isDisabled" />
        <!-- <a-select v-model:value="model.visitor" allowClear placeholder="请选择到访者" :disabled="model.id">
          <template v-for="(item, index) in userList" :key="index">
            <a-select-option :value="item.username">
              {{ item.realname }}
            </a-select-option>
          </template>
        </a-select> -->
      </a-form-item>
      <a-form-item label="访问站点" name="stationCode">
        <a-select v-model:value="model.stationCode" allowClear placeholder="请选择站点" :disabled="isDisabled">
          <template v-for="(item, index) in stationList" :key="index">
            <a-select-option :value="item.stationCode">
              {{ item.name }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="身份证号码" name="visitorIdentity">
        <a-input v-model:value="model.visitorIdentity" allowClear placeholder="身份证号码" :disabled="isDisabled" />
      </a-form-item>
      <a-form-item label="电话号码" name="visitorTel">
        <a-input v-model:value="model.visitorTel" allowClear placeholder="电话号码" :disabled="isDisabled" />
      </a-form-item>
      <a-form-item label="到访人数" name="visitorCount">
        <a-input type="number" :min="0" v-model:value="model.visitorCount" allowClear placeholder="请输入到访人数" :disabled="isDisabled" />
      </a-form-item>
      <a-form-item label="被访员工" name="visitEmployee">
        <a-select v-model:value="model.visitEmployee" allowClear placeholder="请选择被访员工" :disabled="isDisabled">
          <template v-for="(item, index) in userList" :key="index">
            <a-select-option :value="item.realname">
              {{ item.realname }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="到访时间" name="visitTime">
        <a-date-picker
          v-model:value="model.visitTime"
          valueFormat="YYYY-MM-DD hh:mm:ss"
          show-time
          placeholder="请输入到访时间"
          :disabled="isDisabled"
        />
      </a-form-item>
      <a-form-item label="到访事由" name="visitReason">
        <a-textarea v-model:value="model.visitReason" allowClear placeholder="请输入到访事由" :disabled="isDisabled" :rows="3" />
      </a-form-item>
      <a-form-item label="车牌号码" name="licence">
        <a-input v-model:value="model.licence" allowClear placeholder="请输入车牌号码" :disabled="isDisabled" />
      </a-form-item>
      <a-form-item label="自拍照片" name="attachment">
        <template v-if="model.attachment">
          <Image :width="100" :src="model.attachment" />
        </template>
        <template v-else>
          <a-upload
            name="file"
            :action="ossAction"
            v-model:file-list="fileList"
            list-type="picture-card"
            :headers="tokenHeader"
            :showUploadList="true"
            :disabled="isDisabled"
            @change="handleUploadChange"
          >
            <div class="flex items-center justify-end upload-form-item" title="点击上传文件">
              <i class="ico"></i>
              <span>上传</span>
            </div>
          </a-upload>
        </template>
      </a-form-item>
      <a-form-item label="身份证正面图片" name="identityFront">
        <template v-if="model.identityFront">
          <Image :width="100" :src="model.identityFront" />
        </template>
        <template v-else>
          <a-upload
            name="file"
            :action="ossAction"
            v-model:file-list="identityFrontImages"
            list-type="picture-card"
            :headers="tokenHeader"
            :showUploadList="true"
            :disabled="isDisabled"
            @change="uploadIdentityFront"
          >
            <div class="flex items-center justify-end upload-form-item" title="点击上传文件">
              <i class="ico"></i>
              <span>上传</span>
            </div>
          </a-upload>
        </template>
      </a-form-item>
      <a-form-item label="身份证反面图片" name="identityBack">
        <template v-if="model.identityBack">
          <Image :width="100" :src="model.identityBack" />
        </template>
        <template v-else>
          <a-upload
            name="file"
            :action="ossAction"
            v-model:file-list="identityBackImages"
            list-type="picture-card"
            :headers="tokenHeader"
            :showUploadList="true"
            :disabled="isDisabled"
            @change="uploadIdentityBack"
          >
            <div class="flex items-center justify-end upload-form-item" title="点击上传文件">
              <i class="ico"></i>
              <span>上传</span>
            </div>
          </a-upload>
        </template>
      </a-form-item>
      <template v-if="model.visitStatus == 2">
        <a-form-item label="离场时间">
          <a-input v-model:value="model.leaveTime" allowClear placeholder="请输入车牌号码" disabled />
        </a-form-item>
      </template>
      <a-form-item label="操作">
        <a-button @click="resetForm" v-show="!model.id">重置</a-button>
        <a-divider type="vertical" v-show="!model.id" />
        <a-button type="primary" html-type="submit" v-show="!model.id">提交保存</a-button>
        <template v-if="model.visitStatus == 0">
          <a-button type="primary" @click="confirmVisit" v-auth="'visit:confirm'">确认访问</a-button>
        </template>
        <template v-else-if="model.visitStatus == 1 && isSecure">
          <a-button type="primary" @click="handleConfirm">确认离场</a-button>
        </template>
      </a-form-item>
    </a-form>
    <CommonAMap ref="commonAMap" @oks="getMapData" />
  </a-drawer>
</template>

<script lang="ts">
import { watch, ref, nextTick, computed, defineComponent, getCurrentInstance } from 'vue';
import { JDictSelectTag } from '/@/components/Form';
import { visitInfoApi, visitAddApi, visitModifyApi, confirmVistitApi, leaveVistitApi } from '/@/api/visit';
import { projectListApi } from '@/api/project';
import CommonAMap from '/@/components/CommonAMap/index.vue';
import { useUserStore } from '/@/store/modules/user';
import { Empty, Image, message } from 'ant-design-vue';
import { listAllByUserDepartApi } from '/@/api/sys/user';
import { useGlobSetting } from '/@/hooks/setting';
import { getToken } from '/@/utils/auth';
export default defineComponent({
  components: { JDictSelectTag, CommonAMap, Image },
  props: {
    stationList: {
      type: Object,
      default: [],
    },
    // userList: {
    //   type: Object,
    //   defalut: [],
    // },
  },
  setup(props, { emit }) {
    const userStore = useUserStore();
    const tokenHeader = { 'X-Access-Token': getToken() };
    let { proxy } = getCurrentInstance();
    let visible = ref(false);
    let model = ref({
      visitor: '',
      stationCode: '',
      visitorTel: '',
      visitorCount: '',
      visitEmployee: '',
      visitReason: '',
      licence: '',
      // 自拍照片
      attachment: '',
      // 身份证正面
      identityFront: '',
      // 身份证反面
      identityBack: '',
    });

    const glob = useGlobSetting();
    const ossAction = computed(() => `${glob.uploadUrl}/sys/common/upload`);

    let isDisabled = computed(() => {
      if (model.value.id) {
        return true;
      } else {
        return false;
      }
    });

    let isSecure = computed(() => {
      if (userStore.getUserInfo['roleCodes'] == 'SECURE') {
        return true;
      } else {
        return false;
      }
    });

    let fileList = ref([]);

    // 身份证正面图片
    let identityFrontImages = ref([]);

    // 身份证反面图片
    let identityBackImages = ref([]);

    let regionList = ref([]);
    let rules = ref({
      visitor: [{ required: true, message: '请选择访客姓名' }],
      stationCode: [{ required: true, message: '请选择站点' }],
      visitTime: [{ required: true, message: '请选择到访时间' }],
      attachment: [{ required: true, message: '请上传自拍照片' }],
      identityFront: [{ required: true, message: '请上传身份证正面' }],
      identityBack: [{ required: true, message: '请上传身份证反面' }],
    });

    let projectList = ref([]);

    // 用户列表
    let userList = ref([]);

    function getRegionData(data: []) {
      regionList.value = data;
    }

    /**
     * 初始化数据
     * @param {number} id
     */
    function init(id) {
      fileList.value = [];
      identityFrontImages.value = [];
      identityBackImages.value = [];
      visitInfoApi({ id }).then((res) => {
        res['state'] = res['state'] + '';
        res['alarmState'] = res['alarmState'] + '';
        let { attachment, identityFront, identityBack } = res;
        if (attachment) {
          let map = attachment.split('/');
          fileList.value = [
            {
              name: map[map.length - 1],
              status: 'done',
              url: attachment,
            },
          ];
        }
        if (identityFront) {
          let map = identityFront.split('/');
          identityFrontImages.value = [
            {
              name: map[map.length - 1],
              status: 'done',
              url: identityFront,
            },
          ];
        }
        if (identityBack) {
          let map = identityBack.split('/');
          identityBackImages.value = [
            {
              name: map[map.length - 1],
              status: 'done',
              url: identityBack,
            },
          ];
        }
        model.value = { ...res };
      });
    }

    function resetForm() {
      proxy.$refs.formRef.resetFields();
    }

    /**
     * 初始化项目列表
     */
    function initProjectList() {
      projectListApi({}).then((res) => {
        projectList.value = res;
      });
    }

    function onFinish() {
      let list = fileList.value.map((item) => item.url);
      let data = {
        ...model.value,
        attachment: list.join(','),
      };
      if (!data['id']) {
        visitAddApi(data).then((res) => {
          if (res) {
            proxy.$refs.formRef.resetFields();
            visible.value = false;
            message.success('操作成功');
            fileList.value = [];
            emit('oks');
          }
        });
      } else {
        visitModifyApi(data).then((res) => {
          if (res) {
            proxy.$refs.formRef.resetFields();
            visible.value = false;
            userStore.setRequestvisit();
            fileList.value = [];
            emit('oks');
          }
        });
      }
    }

    /**
     * 上传成功后组将成文件列表
     */
    function handleUploadChange(e) {
      if (e.file.status == 'removed') {
        fileList.value = [];
        model.value.attachment = '';
      } else {
        if (e.file.response) {
          fileList.value = [];
          let fileName = e.file.response.message;
          const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
          let url = `http://27.45.145.110:3200/api/${fileName}`;
          model.value.attachment = url;
          fileList.value.push({
            name: fileName,
            url,
            type: `.${fileExtension}`,
          });
        }
      }
    }

    function uploadIdentityFront(e) {
      if (e.file.status == 'removed') {
        identityFrontImages.value = [];
        model.value.identityFront = '';
      } else {
        if (e.file.response) {
          identityFrontImages.value = [];
          let fileName = e.file.response.message;
          const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
          let url = `http://27.45.145.110:3200/api/${fileName}`;
          model.value.identityFront = url;
          identityFrontImages.value.push({
            name: fileName,
            url,
            type: `.${fileExtension}`,
          });
        }
      }
    }

    function uploadIdentityBack(e) {
      if (e.file.status == 'removed') {
        identityFrontImages.value = [];
        model.value.identityBack = '';
      } else {
        if (e.file.response) {
          identityBackImages.value = [];
          let fileName = e.file.response.message;
          const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
          let url = `http://27.45.145.110:3200/api/${fileName}`;
          model.value.identityBack = url;
          identityBackImages.value.push({
            name: fileName,
            url,
            type: `.${fileExtension}`,
          });
        }
      }
    }

    /**
     * 打开地图
     */
    function openMap() {
      proxy.$refs.commonAMap.visible = true;
      nextTick(() => {
        proxy.$refs.commonAMap.initMap(model.value);
      });
    }

    /**
     * 初始化用户列表
     */
    function initListAllByUserDepart() {
      listAllByUserDepartApi().then((res) => {
        userList.value = res.records;
      });
    }

    /**
     * 确定离场操作
     */
    function handleConfirm() {
      let data = {
        confirmState: 1,
        id: model.value.id,
      };
      leaveVistitApi(data).then((res) => {
        if (res) {
          visible.value = false;
          emit('oks');
        }
      });
    }

    watch(
      () => visible.value,
      (v) => {
        if (v) {
          fileList.value = [];
          identityFrontImages.value = [];
          identityBackImages.value = [];
          initProjectList();
          initListAllByUserDepart();
        }
        if (!v) {
          model.value = {
            id: '',
            visitor: '',
            stationCode: '',
            visitorTel: '',
            visitorCount: '',
            visitEmployee: '',
            visitReason: '',
            licence: '',
          };
          delete model.value.id;
        }
      },
      { deep: true }
    );

    /**
     * 获取地图返回的经纬度
     */
    function getMapData({ longitue, latitude }) {
      Object.assign(model.value, {
        longitue,
        latitude,
      });
      AMap.plugin('AMap.Geocoder', () => {
        new AMap.Geocoder().getAddress([longitue, latitude], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            model.value.address = result.regeocode.formattedAddress;
          }
        });
      });
    }

    function showDrawer(data: {}) {
      visible.value = true;
      if (data) {
        model.value = data;
        console.log(model.value);
      }
    }

    function confirmVisit() {
      confirmVistitApi({ id: model.value.id }).then((res) => {
        message.success('操作成功');
        visible.value = false;
        emit('oks');
      });
    }

    return {
      init,
      visible,
      model,
      rules,
      projectList,
      regionList,
      userList,
      isDisabled,
      ossAction,
      fileList,
      tokenHeader,
      isSecure,
      identityFrontImages,
      identityBackImages,
      resetForm,
      onFinish,
      openMap,
      getMapData,
      getRegionData,
      showDrawer,
      confirmVisit,
      handleUploadChange,
      handleConfirm,
      uploadIdentityFront,
      uploadIdentityBack,
    };
  },
});
</script>
